package spms.front.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Component
public class Invoker{

    private Logger logger = LoggerFactory.getLogger(getClass());

    public static final Invoker INSTANCE = new Invoker();

    private static LoadBalancerClient loadBalancerClient;
    private static RestTemplate restTemplate;

    public <T> T invoke(String serverName,String method,MultiValueMap mapParam,Class<T> t){
        try{
            ServiceInstance si = loadBalancerClient.choose(serverName);
            StringBuffer sb = new StringBuffer();
            sb.append("http://").append(si.getHost()).append(":").append(si.getPort()).append("/").append(serverName).append(method);
            logger.info("请求地址：{},入参：{}",sb.toString(),mapParam);
            T result = restTemplate.postForObject(sb.toString() ,mapParam, t);
            logger.info("请求地址：{},入参：{},成功返回：{}",sb.toString(),mapParam,result);
            return result;
        }catch (Exception e){
            logger.error("调用接口报错",e);
        }
        return null;
    }

    @Autowired
    public void setLoadBalancerClient(LoadBalancerClient loadBalancerClient) {
        Invoker.loadBalancerClient = loadBalancerClient;
    }
    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        Invoker.restTemplate = restTemplate;
    }
}
